package com.hhf.feiapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hhf.feiapiclientsdk.entity.User;
import com.hhf.feiapiclientsdk.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hhf
 * @Date 2024/10/5
 * @Description
 */
@Slf4j
public class HelloClient {

    private String accessKey;

    private String secretKey;

    public HelloClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }


    private String BASEURL = "http://localhost:8082/api";

    public String getTextByGet(String name) {

        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        String result = HttpUtil.get(BASEURL + "/hello", map);
        log.info(result);
        return result;
    }

    public String getTextByPost(String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        String result = HttpUtil.post(BASEURL + "/hello", map);
        log.info(result);
        return result;
    }

    public String getTextByPostJson(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);



        HttpResponse response = HttpRequest.post(BASEURL + "/hello/body")
                .body(jsonStr)
                .addHeaders(this.getKeyMap(jsonStr))
                .execute();
        String result = response.body();
        log.info(result);
        return result;
    }

    private Map<String,String> getKeyMap(String body){
        Map<String,String> map = new HashMap<>();
        map.put("accessKey",accessKey);//参数1:accessKey
//        map.put("secretKey",secretKey);//参数2:secretKey        不能直接发送密钥
        map.put("body",body);//参数3:请求参数
        map.put("nonce", RandomUtil.randomNumbers(5));//参数4:随机数
        map.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));//参数5:时间戳

        String sign = SignUtils.genSign(body, secretKey);        //密钥用来生成sign
        map.put("sign", sign);
        return map;
    }


}
